#include "billtemplate.h"

BillTemplate::BillTemplate()
    : templateName("默认模板"),
      templateWidth(210),
      templateHeight(297)
{
}

void BillTemplate::addField(const QString& name, float x, float y, float width, float height, float fontSize)
{
    FieldInfo field;
    field.name = name;
    field.x = x;
    field.y = y;
    field.width = width;
    field.height = height;
    field.fontSize = fontSize;
    
    fields.append(field);
}

bool BillTemplate::saveToFile(const QString& filename)
{
    QJsonObject data;
    data["template_name"] = templateName;
    data["template_width"] = templateWidth;
    data["template_height"] = templateHeight;
    
    QJsonArray fieldsArray;
    for (const auto& field : fields) {
        QJsonObject fieldObj;
        fieldObj["name"] = field.name;
        fieldObj["x"] = field.x;
        fieldObj["y"] = field.y;
        fieldObj["width"] = field.width;
        fieldObj["height"] = field.height;
        fieldObj["font_size"] = field.fontSize;
        fieldsArray.append(fieldObj);
    }
    
    data["fields"] = fieldsArray;
    
    QJsonDocument doc(data);
    QFile file(filename);
    
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件进行写入:" << filename;
        return false;
    }
    
    file.write(doc.toJson(QJsonDocument::Indented));
    file.close();
    
    return true;
}

BillTemplate BillTemplate::loadFromFile(const QString& filename)
{
    BillTemplate templateObj;
    
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件进行读取:" << filename;
        return templateObj;
    }
    
    QByteArray data = file.readAll();
    file.close();
    
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        qDebug() << "JSON解析错误";
        return templateObj;
    }
    
    QJsonObject obj = doc.object();
    
    templateObj.templateName = obj["template_name"].toString("默认模板");
    templateObj.templateWidth = obj["template_width"].toDouble(210);
    templateObj.templateHeight = obj["template_height"].toDouble(297);
    
    QJsonArray fieldsArray = obj["fields"].toArray();
    templateObj.fields.clear();
    
    for (const auto& fieldValue : fieldsArray) {
        QJsonObject fieldObj = fieldValue.toObject();
        FieldInfo field;
        field.name = fieldObj["name"].toString();
        field.x = fieldObj["x"].toDouble();
        field.y = fieldObj["y"].toDouble();
        field.width = fieldObj["width"].toDouble();
        field.height = fieldObj["height"].toDouble();
        field.fontSize = fieldObj["font_size"].toDouble();
        
        templateObj.fields.append(field);
    }
    
    return templateObj;
}
